package com.example.logindb.controller;



import com.example.logindb.dto.ResponseMessage;
import com.example.logindb.entity.Location;
import com.example.logindb.sevices.LocationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

//错了，看其他controller
@RestController
@RequestMapping("/route")
public class RouteController {
    @Autowired
    LocationService locationService;

    private String uploadPath = System.getProperty("user.dir") + "/obdetect/Input";
    //更新在线位置
    @PostMapping
    public ResponseMessage<Location> updateStatus(@RequestBody Location location)
    {
        locationService.updateLocation(location);
        return ResponseMessage.success(location);
    }
    @PostMapping("/upload")
    public String uploadFile(@RequestParam("image") MultipartFile file,
                             @RequestParam("id") String id){
        try {
            // 获取文件名
            String fileName = file.getOriginalFilename();
            // 指定保存路径
            String filePath = uploadPath + "/" + id + "/" + fileName;
            // 保存文件到本地
            file.transferTo(new File(filePath));
            // 向 Python 发送处理请求
            URL url = new URL("http://localhost:8100/" + id);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer content = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            in.close();
            con.disconnect();

            System.out.println(content);

            return content.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "Fail";
        }
    }


}
